<?php
declare (strict_types = 1);

namespace app\controller\api;

use app\BaseController;
use app\model\Code as CodeModel;
use think\facade\Session;

class Code extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        // 检查管理员登录状态
        if (!Session::has('admin_id')) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }
    }
    
    /**
     * 获取赋码列表
     */
    public function index()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $status = input('status/d', -1);
        
        $where = [];
        if ($status >= 0) {
            $where['status'] = $status;
        }
        
        $list = CodeModel::getPageList($where, $page, $limit);
        return json(['code' => 0, 'data' => $list]);
    }
    
    /**
     * 生成赋码
     */
    public function generate()
    {
        $count = input('count/d', 1);
        if ($count < 1 || $count > 100) {
            return json(['code' => 1, 'msg' => '生成数量必须在1-100之间']);
        }
        
        $codes = [];
        for ($i = 0; $i < $count; $i++) {
            $code = CodeModel::generateCode();
            $qrcode = (new CodeModel)->generateQrcode($code);
            
            $codes[] = [
                'code' => $code,
                'qrcode' => $qrcode,
                'status' => 0
            ];
        }
        
        CodeModel::insertAll($codes);
        return json(['code' => 0, 'msg' => '生成成功']);
    }
    
    /**
     * 删除赋码
     */
    public function delete()
    {
        $id = input('id/d');
        if (!$id) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $code = CodeModel::find($id);
        if (!$code) {
            return json(['code' => 1, 'msg' => '赋码不存在']);
        }
        
        // 删除二维码文件
        if ($code->qrcode && file_exists(public_path() . $code->qrcode)) {
            unlink(public_path() . $code->qrcode);
        }
        
        $code->delete();
        return json(['code' => 0, 'msg' => '删除成功']);
    }
    
    /**
     * 批量删除赋码
     */
    public function batchDelete()
    {
        $ids = input('ids/a');
        if (empty($ids)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $codes = CodeModel::whereIn('id', $ids)->select();
        foreach ($codes as $code) {
            // 删除二维码文件
            if ($code->qrcode && file_exists(public_path() . $code->qrcode)) {
                unlink(public_path() . $code->qrcode);
            }
        }
        
        CodeModel::whereIn('id', $ids)->delete();
        return json(['code' => 0, 'msg' => '删除成功']);
    }
} 